package project.messagestack;

import java.io.IOException;
import java.util.ArrayList;

import project.messagestack.GUI.Preferences;
import project.messagestack.network.ConnectionHandler;
import project.messagestack.network.facebook.FacebookConnect;
import project.messagestack.network.imap.IMAP;
import project.messagestack.network.pop3.POP3;
import project.messagestack.utils.DatabaseManager;
import project.messagestack.utils.Logger;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.shapes.Shape;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class message_stack extends ListActivity implements OnSharedPreferenceChangeListener {
  private DatabaseManager db;
  private ArrayList<ConnectionHandler> list;
  final String[] items = {"SMS & MMS", "Facebook", "Nasza-Klasa", "Twitter",
      "Buzz"};
  String selected = "";
  String result = "";
  String findText = "";
  Intent intent;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    db = new DatabaseManager(this);
    startService(new Intent(this, MessageStackService.class));
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    preferences.registerOnSharedPreferenceChangeListener(this);
    list=new ArrayList<ConnectionHandler>();
    intent=new Intent(getApplicationContext(), FacebookConnect.class);
    db = new DatabaseManager(this);
    //Cursor cur = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
    //     ContactsContract.Contacts.DISPLAY_NAME + " <> \"\"", null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    //Cursor c = managedQuery(Uri.parse("content://sms/inbox"), null, null, null, null);
    //startManagingCursor(cur);
    
    populateMsgsList();
    
  }
    
  private void populateMsgsList() {
    AdapterView lv = (AdapterView) findViewById(android.R.id.list);
    lv.removeAllViewsInLayout();
 
    Cursor c = new DatabaseManager(this).getMessagesToDisplay();
    ListAdapter la = new MessageCursorAdapter(this, R.layout.list_layout, c,
        new String[]{"address","body", "service"}, new int[]{R.id.ListUserName, R.id.ListMessageContent, R.id.ListService});
    setListAdapter(la);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
      case R.id.main_screen_preferences :
        handlePreferencesDecision();
        break;
      case R.id.main_screen_update_now:      
        intent = new Intent(this, MessageStackService.class);
        intent.putExtra(MessageStackService.UPDATE_SERVICES_NOW, 1);
        startService(intent);
        break;
      case R.id.main_screen_quit:
        handleExitDecision();
      case R.id.main_screen_favorites:
        if(db.getServicesConfiguration().getCount()!=list.size()){
          list.clear();
          Cursor a = db.getServicesConfiguration();
          a.moveToFirst();
          while (!a.isAfterLast()) {
            if (a.getString(1).startsWith("MAIL")) {
              String temp = a.getString(2);
              String content[] = temp.split(":");
              ContentValues cv = new ContentValues();
              cv.put("username", content[0]);
              cv.put("password", content[1]);
              cv.put("hostname", content[2]);
              cv.put("mailbox", "inbox");
              cv.put("usessl", true);
              cv.put("port", Integer.parseInt(content[3]));
              ConnectionHandler acount;
              if (content[4].equals("IMAP")) {
                acount = new IMAP(db);
                acount.prepareConnection(cv);
                acount.updateData();
                acount.stopConnection();
              } else {
                acount = new POP3(db);
                acount.prepareConnection(cv);
                acount.updateData();
                acount.stopConnection();
              }
              list.add(acount);
            }
            a.moveToNext();
         
          }
        }else{
          for(int i =0 ;i<list.size();i++){
            ContentValues cv =list.get(i).getHandlerConfiguration();
            list.get(i).prepareConnection(cv);
            list.get(i).updateData();
            list.get(i).stopConnection();
          }
        }
        break;
      case R.id.main_screen_search:
        intent = new Intent(this, FacebookConnect.class);
        startActivity(intent);
        break;
      default:
        Logger.logWarn("Unknown menu event triggered");
    }
    return true;
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK && requestCode == 0) {
      Toast.makeText(this, data.toURI(), Toast.LENGTH_LONG);
    }
  }
 
  @Override
  protected void onResume(){
	  	super.onResume();
	  	
	    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
	    //ImageView mainv = (ImageView)findViewById(R.id.MAINbg);
	    RelativeLayout rl = (RelativeLayout)findViewById(R.id.relativeLayout);
	    rl.setWillNotDraw(false);
		if(preferences.getString("colorSettings", "null").equalsIgnoreCase("Dark Color")){
			rl.setBackgroundResource(R.drawable.bg_normal);
		}
		else if(preferences.getString("colorSettings", "null").equalsIgnoreCase("Bright Color")){
			rl.setBackgroundResource(R.drawable.bg_normal_br);
		}
		else if(preferences.getString("colorSettings", "null").equalsIgnoreCase("Blue Color")){
			rl.setBackgroundResource(R.drawable.bg_normal_bl);
		}
		else if(preferences.getString("colorSettings", "null").equalsIgnoreCase("Green Color")){
			rl.setBackgroundResource(R.drawable.bg_normal_gr);
		}
		else if(preferences.getString("colorSettings", "null").equalsIgnoreCase("Red Color")){
			rl.setBackgroundResource(R.drawable.bg_normal_re);
		}
		rl.invalidate();
  }
  
  private void handleExitDecision() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?").setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            Intent intent = new Intent(message_stack.this, MessageStackService.class);
            stopService(intent);
            finish();
          }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
          }
        });
    AlertDialog alertExt = builder.create();
    alertExt.show();
  }
  
  public void handleViewClick(View view) {
    if (view.getId() != R.id.ListItemLayout) {
      view = (View) view.getParent();
    }
    Intent i = new Intent(this, MessageView.class);
    i.putExtra("user", ((TextView)view.findViewById(R.id.ListUserName)).getText());
    i.putExtra("content", ((TextView)view.findViewById(R.id.tempTV)).getText());
    i.putExtra("phone", ((TextView)view.findViewById(R.id.tempTV2)).getText());
    i.putExtra("service", ((TextView)view.findViewById(R.id.ListService)).getText());
    startActivity(i);
  }
 
  private void handlePreferencesDecision() {
    Intent intent = new Intent(this, Preferences.class);
    startActivity(intent);
  }

  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
      String key) {
    populateMsgsList();
  }
  
}
